package com.zywl.web.controller.sys;

import com.zywl.core.beans.Company;
import com.zywl.core.beans.Member;
import com.zywl.core.beans.User;
import com.zywl.service.CompanyService;
import com.zywl.service.MemberService;
import com.zywl.utils.models.AjaxResult;
import com.zywl.utils.models.PageData;
import com.zywl.utils.models.PageResult;
import com.zywl.utils.utils.Constants;
import com.zywl.utils.utils.MapUtil;
import com.zywl.utils.utils.enums.LogTypeEnum;
import com.zywl.web.controller.base.BaseController;
import com.zywl.web.controller.form.MemberForm;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/member")
public class MemberController extends BaseController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private CompanyService companyService;

    @GetMapping("/memberListPage")
    public ModelAndView memberListPage() {
        ModelAndView mav = new ModelAndView("member/memberListPage");
        return mav;
    }


    @PostMapping("/getMemberList")
    public PageResult getMemberList(HttpServletRequest request, PageData pageData) {

        Map<String, Object> condition = MapUtil.changeMap(request.getParameterMap());
        PageResult pageResult = null;
        try {
//            condition.put("mebStt","0");
            pageResult = putToResult(memberService.getPageInfo(condition, pageData));
            List<Member> list = pageResult.getData();
            List<MemberForm> memberFormList = new ArrayList<>();
            List<Long> longList = new ArrayList<>();
            for (Member member : list){
                longList.add(member.getMebCompanyId());
            }
            List<Company> companylist = companyService.getListByList(longList);
            for (Member member : list){
                MemberForm form = new MemberForm();
                BeanUtils.copyProperties(member,form);
                for (Company company : companylist){
                    if(member.getMebCompanyId() == company.getComId()){
                        form.setMebCompanyName(company.getComName());
                    }
                }
                memberFormList.add(form);
            }
            pageResult.setData(memberFormList);
        } catch (Exception e) {
            logger.error("获取会员列表异常", e);
        }


        return pageResult;
    }


    @GetMapping("/updateState")
    public AjaxResult updateState(Long id) {
        AjaxResult ar = new AjaxResult();
        try {
            Member member = memberService.getById(id);
            if (member != null) {
                if ("1".equals(member.getMebStt())) {
                    member.setMebStt("0");
                    memberService.update(member);
                    ar.success("启用成功");
                } else {
                    member.setMebStt("1");
                    memberService.update(member);
                    ar.success("禁用成功");
                }
            }
        } catch (Exception e) {
            logger.error("修改用户状态异常", e);
            ar.error("修改用户状态异常");
        }
        return ar;
    }

    @GetMapping("/memberSubmitPage")
    public ModelAndView memberSubmitPage(String id) {
        ModelAndView mav = new ModelAndView("member/memberSubmitPage");
        try {
            if (StringUtils.isNotEmpty(id)) {
                Member member = memberService.getById(Long.parseLong(id));
                mav.addObject("member", member);
            }
        } catch (Exception e) {
            logger.error("获取数据异常", e);
        }
        return mav;
    }

    @PostMapping("/memberSubmit")
    public AjaxResult memberSubmit(HttpServletRequest request, Member form) {
        AjaxResult ar = new AjaxResult();
        if (form != null) {
            Member member = null;
            String old = null;
            Date date = new Date();
            try {
                if (form.getMebId() != null) {
                    member = memberService.getById(form.getMebId());
                    old = member.getMebNickname();
                    form.setMebStt(member.getMebStt());
                    form.setMebCreateTime(member.getMebCreateTime());
                } else {
                    member = new Member();
                    form.setMebStt("0");
                    form.setMebCreateTime(date);

                    User user = (User) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
                    if (user.getUsrAssociationId() != null){
                        form.setMebAssociationId(user.getUsrAssociationId());
                    }else{
                        ar.error("平台管理员无法帮忙创建会员");
                        return ar;
                    }

                    //查询公司名称是否已存在
                    Map<String, Object> condition = new HashMap<>();
                    condition.put("mebUsername",form.getMebMobile());
                    condition.put("mebStt","0");
                    int count = memberService.getCountByParams(condition);
                    if(count > 0){
                        ar.error("该号码作为账户已存在，请修改");
                        return ar;
                    }
                }

                form.setMebModifyTime(date);
                BeanUtils.copyProperties(form, member);

                if (form.getMebId() == null) {
                    memberService.save(member);
                } else {
                    memberService.update(member);
                }
            } catch (Exception e) {
                logger.error("提交会员信息异常", e);
                ar.error("提交会员信息异常", e);
                return ar;
            }

            if (form.getMebId() == null) {
                saveLog(request, LogTypeEnum.MEMBER.getKey(), "会员新增-" + form.getMebNickname());
                ar.success("新增成功");
            } else if (old != null && !old.equals(form.getMebNickname())) {
                saveLog(request, LogTypeEnum.MEMBER.getKey(), "会员修改-" + old + "→" + form.getMebNickname());
                ar.success("修改成功");
            } else {
                saveLog(request, LogTypeEnum.MEMBER.getKey(), "会员修改-" + form.getMebNickname());
                ar.success("修改成功");
            }
        } else {
            ar.error("提交失败，参数为空");
        }
        return ar;
    }

    @PostMapping("/memberDelete")
    public AjaxResult memberDelete(HttpServletRequest request, Long id) {
        AjaxResult ar = new AjaxResult();
        try {
            Member member = memberService.getById(id);
            String memberNickName = member.getMebNickname();
            member.setMebStt("2");
            memberService.update(member);//逻辑删除用户
            saveLog(request, LogTypeEnum.MEMBER.getKey(), "会员信息删除-" + memberNickName);
            ar.success("删除成功");
        } catch (Exception e) {
            ar.error("删除会员异常", e);
            logger.error("删除会员异常", e);
        }
        return ar;
    }

    @GetMapping("/resetPassword")
    public AjaxResult resetPassword(HttpServletRequest request,Long id) {//管理员重置密码
        AjaxResult ar = new AjaxResult();
        try {
            Member member = memberService.getById(id);
            saveLog(request, LogTypeEnum.MEMBER.getKey(), "重置密码" + member.getMebUsername());
            ar.success("重置密码成功");
        } catch (Exception e) {
            logger.error("重置密码异常", e);
            ar.error("重置密码异常");
        }
        return ar;
    }

}
